// 游戏常量
const BOARD_SIZE = 15; // 15x15的棋盘
const CELL_SIZE = 40; // 每个格子的大小（像素）
const PIECE_RADIUS = CELL_SIZE / 2 - 2; // 棋子半径

// 获取DOM元素
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const restartButton = document.getElementById('restart');
const undoButton = document.getElementById('undo');
const statusElement = document.querySelector('.status');
const blackPlayerElement = document.querySelector('.player.black');
const whitePlayerElement = document.querySelector('.player.white');
const winModal = document.getElementById('win-modal');
const winMessage = document.getElementById('win-message');
const newGameButton = document.getElementById('new-game');

// 游戏状态
let gameBoard = []; // 存储棋盘状态：0-空，1-黑棋，2-白棋
let currentPlayer = 1; // 当前玩家：1-黑棋，2-白棋
let gameOver = false; // 游戏是否结束
let moveHistory = []; // 移动历史记录

// 初始化游戏
function initGame() {
    // 初始化棋盘
    gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
    
    // 重置游戏状态
    currentPlayer = 1;
    gameOver = false;
    moveHistory = [];
    
    // 更新UI
    updatePlayerInfo();
    updateStatus();
    
    // 绘制棋盘
    drawBoard();
    
    // 隐藏胜利弹窗
    winModal.classList.remove('show');
    
    // 启用悔棋按钮
    undoButton.disabled = true;
}

// 绘制棋盘
function drawBoard() {
    // 设置画布大小
    canvas.width = CELL_SIZE * BOARD_SIZE;
    canvas.height = CELL_SIZE * BOARD_SIZE;
    
    // 绘制棋盘背景
    ctx.fillStyle = '#e6c88e';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格线
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 1;
    
    // 绘制横线和竖线
    for (let i = 0; i < BOARD_SIZE; i++) {
        // 横线
        ctx.beginPath();
        ctx.moveTo(CELL_SIZE / 2, i * CELL_SIZE + CELL_SIZE / 2);
        ctx.lineTo(canvas.width - CELL_SIZE / 2, i * CELL_SIZE + CELL_SIZE / 2);
        ctx.stroke();
        
        // 竖线
        ctx.beginPath();
        ctx.moveTo(i * CELL_SIZE + CELL_SIZE / 2, CELL_SIZE / 2);
        ctx.lineTo(i * CELL_SIZE + CELL_SIZE / 2, canvas.height - CELL_SIZE / 2);
        ctx.stroke();
    }
    
    // 绘制天元和星位
    const starPoints = [
        [3, 3], [3, 7], [3, 11],
        [7, 3], [7, 7], [7, 11],
        [11, 3], [11, 7], [11, 11]
    ];
    
    ctx.fillStyle = '#000';
    starPoints.forEach(point => {
        const [x, y] = point;
        ctx.beginPath();
        ctx.arc(
            x * CELL_SIZE + CELL_SIZE / 2,
            y * CELL_SIZE + CELL_SIZE / 2,
            3, 0, Math.PI * 2
        );
        ctx.fill();
    });
    
    // 绘制所有已放置的棋子
    for (let y = 0; y < BOARD_SIZE; y++) {
        for (let x = 0; x < BOARD_SIZE; x++) {
            if (gameBoard[y][x] !== 0) {
                drawPiece(x, y, gameBoard[y][x]);
            }
        }
    }
}

// 绘制棋子
function drawPiece(x, y, player) {
    const centerX = x * CELL_SIZE + CELL_SIZE / 2;
    const centerY = y * CELL_SIZE + CELL_SIZE / 2;
    
    // 绘制阴影
    ctx.beginPath();
    ctx.arc(centerX + 2, centerY + 2, PIECE_RADIUS, 0, Math.PI * 2);
    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
    ctx.fill();
    
    // 绘制棋子
    ctx.beginPath();
    ctx.arc(centerX, centerY, PIECE_RADIUS, 0, Math.PI * 2);
    
    if (player === 1) { // 黑棋
        // 黑棋渐变
        const gradient = ctx.createRadialGradient(
            centerX - 5, centerY - 5, 1,
            centerX, centerY, PIECE_RADIUS
        );
        gradient.addColorStop(0, '#666');
        gradient.addColorStop(1, '#000');
        ctx.fillStyle = gradient;
    } else { // 白棋
        // 白棋渐变
        const gradient = ctx.createRadialGradient(
            centerX - 5, centerY - 5, 1,
            centerX, centerY, PIECE_RADIUS
        );
        gradient.addColorStop(0, '#fff');
        gradient.addColorStop(1, '#ddd');
        ctx.fillStyle = gradient;
    }
    
    ctx.fill();
    
    // 白棋加边框
    if (player === 2) {
        ctx.strokeStyle = '#999';
        ctx.lineWidth = 1;
        ctx.stroke();
    }
    
    // 标记最后一手棋的位置
    if (moveHistory.length > 0) {
        const lastMove = moveHistory[moveHistory.length - 1];
        if (lastMove.x === x && lastMove.y === y) {
            ctx.beginPath();
            ctx.arc(centerX, centerY, 5, 0, Math.PI * 2);
            ctx.fillStyle = player === 1 ? '#fff' : '#000';
            ctx.fill();
        }
    }
}

// 处理鼠标点击事件
function handleClick(event) {
    if (gameOver) return;
    
    // 获取点击位置
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    // 计算棋盘格子坐标
    const boardX = Math.floor(x / CELL_SIZE);
    const boardY = Math.floor(y / CELL_SIZE);
    
    // 检查坐标是否有效
    if (boardX < 0 || boardX >= BOARD_SIZE || boardY < 0 || boardY >= BOARD_SIZE) {
        return;
    }
    
    // 检查该位置是否已有棋子
    if (gameBoard[boardY][boardX] !== 0) {
        return;
    }
    
    // 放置棋子
    placePiece(boardX, boardY);
}

// 放置棋子
function placePiece(x, y) {
    // 更新棋盘状态
    gameBoard[y][x] = currentPlayer;
    
    // 记录移动
    moveHistory.push({ x, y, player: currentPlayer });
    
    // 启用悔棋按钮
    undoButton.disabled = false;
    
    // 重绘棋盘
    drawBoard();
    
    // 检查胜负
    if (checkWin(x, y, currentPlayer)) {
        gameOver = true;
        showWinMessage(currentPlayer);
        return;
    }
    
    // 切换玩家
    currentPlayer = currentPlayer === 1 ? 2 : 1;
    
    // 更新UI
    updatePlayerInfo();
    updateStatus();
}

// 检查胜负
function checkWin(x, y, player) {
    // 检查方向：水平、垂直、左上到右下、右上到左下
    const directions = [
        { dx: 1, dy: 0 },  // 水平
        { dx: 0, dy: 1 },  // 垂直
        { dx: 1, dy: 1 },  // 左上到右下
        { dx: 1, dy: -1 }  // 右上到左下
    ];
    
    for (const direction of directions) {
        let count = 1;  // 当前位置已经有一个棋子
        
        // 正向检查
        count += countPieces(x, y, direction.dx, direction.dy, player);
        
        // 反向检查
        count += countPieces(x, y, -direction.dx, -direction.dy, player);
        
        // 如果连续5个或更多，则获胜
        if (count >= 5) {
            return true;
        }
    }
    
    return false;
}

// 计算连续棋子数量
function countPieces(x, y, dx, dy, player) {
    let count = 0;
    let currentX = x + dx;
    let currentY = y + dy;
    
    while (
        currentX >= 0 && currentX < BOARD_SIZE &&
        currentY >= 0 && currentY < BOARD_SIZE &&
        gameBoard[currentY][currentX] === player
    ) {
        count++;
        currentX += dx;
        currentY += dy;
    }
    
    return count;
}

// 悔棋
function undoMove() {
    if (moveHistory.length === 0) return;
    
    // 移除最后一步
    const lastMove = moveHistory.pop();
    gameBoard[lastMove.y][lastMove.x] = 0;
    
    // 切换回上一个玩家
    currentPlayer = lastMove.player;
    
    // 如果没有历史记录，禁用悔棋按钮
    if (moveHistory.length === 0) {
        undoButton.disabled = true;
    }
    
    // 如果游戏已结束，重新设置为未结束
    gameOver = false;
    
    // 更新UI
    updatePlayerInfo();
    updateStatus();
    
    // 重绘棋盘
    drawBoard();
}

// 更新玩家信息
function updatePlayerInfo() {
    if (currentPlayer === 1) {
        blackPlayerElement.classList.add('active');
        whitePlayerElement.classList.remove('active');
    } else {
        blackPlayerElement.classList.remove('active');
        whitePlayerElement.classList.add('active');
    }
}

// 更新状态信息
function updateStatus() {
    statusElement.textContent = `轮到${currentPlayer === 1 ? '黑' : '白'}方落子`;
}

// 显示胜利消息
function showWinMessage(player) {
    winMessage.textContent = `${player === 1 ? '黑' : '白'}方获胜！`;
    winModal.classList.add('show');
    statusElement.textContent = `游戏结束，${player === 1 ? '黑' : '白'}方获胜！`;
}

// 事件监听
canvas.addEventListener('click', handleClick);
restartButton.addEventListener('click', initGame);
undoButton.addEventListener('click', undoMove);
newGameButton.addEventListener('click', initGame);

// 窗口大小调整时重新绘制棋盘
window.addEventListener('resize', () => {
    drawBoard();
});

// 初始化游戏
initGame();